package lion.dev.web.useragent;

import org.apache.commons.lang.ArrayUtils;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年5月30日
 */
public class UserAgentToken {

	private String src;
	private int index = 0;
	private int l = 0;
	private int mark = 0;
	private int markl = 0;

	private static char[] tokens = { '(', ' ', ')', ';', ',' };

	public UserAgentToken(String src) {

		this.src = src;
	}

	public void mark() {

		this.mark = this.index;
		this.markl = this.l;
	}

	public boolean isAloneToken() {

		return this.l > 0;
	}

	public void reset() {

		this.index = this.mark;
		this.l = this.markl;
	}

	public String next() {

		if (this.index >= this.src.length()) { return null; }

		int i = this.index;
		for (; this.index < this.src.length(); this.index++) {

			char c = this.src.charAt(this.index);

			if (c == '(') {
				l++;
			} else if (c == ')') {
				l--;
			}
			if (l > 0 && c == ' ') {
				continue;
			}

			if (ArrayUtils.contains(tokens, c)) {
				break;
			}
		}
		if (i == this.index) {
			this.index++;
			return this.next();
		}

		return this.src.substring(i, this.index++);
	}

	public int index() {

		return this.index;
	}

	// public static void main(String[] args) {
	//
	//
	// String userAgent =
	// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)  SEOChat::Bot v1.1";
	// userAgent = " SEOChat::Bot v1.1";
	// // userAgent = "NokiaN97i/SymbianOS/10.22.a.b Series60/3.0";
	// // userAgent =
	// //
	// "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0) AddSugarSpiderBot www.idealobserver.com";
	// // userAgent =
	// //
	// "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Avant Browser; SLCC1;( .NET CLR 2.0.50727; Media Center PC 5.0;) .NET CLR 3.0.04506; .NET CLR 3.5.21022; InfoPath.2)";
	//
	// String tmp;
	// UserAgentToken userAgentToken = new UserAgentToken(userAgent);
	// System.out.println(userAgent.length());
	// System.out.println(userAgentToken.next());
	// System.out.println(userAgentToken.index);
	//
	// // while ((tmp = userAgentToken.next()) != null) {
	// // System.out.println(tmp);
	// // }
	//
	// }
}
